package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.service.EnhancedAIService;
import com.learning.platform.service.UserContextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

/**
 * 增强AI控制器
 * 提供智能化的AI交互接口
 */
@RestController
@RequestMapping("/api/v1/ai/enhanced")
@PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER') or hasRole('ADMIN')")
public class EnhancedAIController {
    
    @Autowired
    private EnhancedAIService enhancedAIService;
    
    @Autowired
    private UserContextService userContextService;
    
    /**
     * 智能问答接口
     */
    @PostMapping("/chat")
    public ResponseEntity<ApiResponse<EnhancedAIService.EnhancedAIResponse>> chat(
            Authentication authentication,
            @RequestBody ChatRequest request) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        try {
            EnhancedAIService.EnhancedAIResponse response = 
                enhancedAIService.processQuery(request.getQuery(), userId);
                
            return ResponseEntity.ok(ApiResponse.success(response, "AI回答生成成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(
                ApiResponse.error(500, "AI服务处理失败：" + e.getMessage())
            );
        }
    }
    
    /**
     * 获取用户学习统计
     */
    @GetMapping("/user-stats")
    public ResponseEntity<ApiResponse<UserContextService.UserLearningStats>> getUserStats(
            Authentication authentication) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        try {
            UserContextService.UserLearningStats stats = 
                userContextService.getUserStats(userId);
                
            return ResponseEntity.ok(ApiResponse.success(stats, "用户学习统计获取成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(
                ApiResponse.error(500, "获取用户统计失败：" + e.getMessage())
            );
        }
    }
    
    /**
     * 更新用户学习偏好
     */
    @PutMapping("/user-preferences")
    public ResponseEntity<ApiResponse<String>> updateUserPreferences(
            Authentication authentication,
            @RequestBody UserPreferencesRequest request) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        try {
            // 更新用户偏好
            if (request.getCurrentLanguage() != null) {
                userContextService.updateCurrentLanguage(userId, request.getCurrentLanguage());
            }
            
            if (request.getLearningGoals() != null) {
                userContextService.updateLearningGoals(userId, request.getLearningGoals());
            }
            
            return ResponseEntity.ok(ApiResponse.success("", "用户偏好更新成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(
                ApiResponse.error(500, "更新用户偏好失败：" + e.getMessage())
            );
        }
    }
    
    /**
     * 聊天请求DTO
     */
    public static class ChatRequest {
        private String query;
        private String context; // 可选的额外上下文
        
        public ChatRequest() {}
        
        public String getQuery() {
            return query;
        }
        
        public void setQuery(String query) {
            this.query = query;
        }
        
        public String getContext() {
            return context;
        }
        
        public void setContext(String context) {
            this.context = context;
        }
    }
    
    /**
     * 用户偏好请求DTO
     */
    public static class UserPreferencesRequest {
        private String currentLanguage;
        private String learningGoals;
        
        public UserPreferencesRequest() {}
        
        public String getCurrentLanguage() {
            return currentLanguage;
        }
        
        public void setCurrentLanguage(String currentLanguage) {
            this.currentLanguage = currentLanguage;
        }
        
        public String getLearningGoals() {
            return learningGoals;
        }
        
        public void setLearningGoals(String learningGoals) {
            this.learningGoals = learningGoals;
        }
    }
}
